﻿define [
    'jquery'
    'use!underscore'
    'use!backbone'
    'album'
    'text!templates/show_photo.html'
    'text!templates/edit_photo.html'
    'jquery_ui'
], ($, _, Backbone, Album, ShowPhotoTemplate, EditPhotoTemplate) ->
  class PhotoView extends Backbone.View
    tagName: 'figure'
    attributes:
      class: 'photo'

    initialize: ->
      @model.on 'error', ((model, err) ->
        console.log err
        @render 'edit'
      ), this
    
    templateFunc:
      show: _.template(ShowPhotoTemplate)
      edit: _.template(EditPhotoTemplate)

    render: (template) ->
      @$el.html @templateFunc[template](@model.toJSON())
      _.each $('.datepicker'), (input) ->
        $(input).datepicker
          dateFormat: 'yy-mm-dd'
          currentText: input.value
      this

    events:
      'click #edit': 'editModel'
      'click #cancel': 'cancelSave'
      'click #save': 'saveUpdate'
      'click #delete': 'deleteModel'

    editModel: (e) ->
      e.preventDefault()
      @render 'edit'

    cancelSave: (e) ->
      e.preventDefault()
      @render 'show'

    saveUpdate: ->
      formData = {}
      @$el.find('input').each ->
        $input = $(this)
        formData[$input.attr('id')] = $input.val()
        
      console.log formData
      console.log @model
      @model.set formData
      @render 'show'

    deleteModel: (e) ->
      e.preventDefault()
      Album.url = '/Photo/Delete'
      @remove()
      @model.destroy()
  #new PhotoView()
